package com.creatified.jacqueline;

import java.io.IOException;
import java.util.List;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class JacquelineWorker extends Thread {
	
	protected final static Logger LOG = Logger.getLogger(JacquelineWorker.class);
	
	private final Jacqueline jacqueline;
	private final List<JacquelineSelector> cssSelectors;
	private final Document doc;
	
	protected JacquelineWorker(Jacqueline jacqueline, Document doc, List<JacquelineSelector> cssSelectors) {
		this.jacqueline = jacqueline;
		this.doc = doc;
		this.cssSelectors = cssSelectors;
	}
	
	public void run() {
		try {
			JacquelineResult result = testDocument();
			
			jacqueline.workerFinished(this, result);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XPathException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			
		}
	}
	
	private JacquelineResult testDocument() throws IOException, XPathException {

		JacquelineResult jackieResult = new JacquelineResult();

		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();

		NodeList nodes = null;

		for(JacquelineSelector selector : cssSelectors) {
			nodes = (NodeList) xpath.compile(selector.getXPathExpression()).evaluate(doc, XPathConstants.NODESET);

			if(nodes != null && nodes.getLength() > 0) {
				/*
				 * WORKAROUND
				 * 'timesUsed' can very big for selectors like '*' (even to big for type long)
				 * so we'll only increment 'timesUsed' by 1 for each document having a match
				 */
				selector.setTimesUsed(1);
			}

			LOG.debug(selector + " was found " + nodes.getLength() + " time(s) in document");

			jackieResult.add(selector);

		}

		return jackieResult;
	}
}
